# -*- coding:UTF-8-*-
from cv2 import cv2
import numpy as np
import struct
from matplotlib import pyplot as plt

width               = 640
hidth               = 512
pix_bit             = 16#每个像素点有8位
IMG_ORIGINAL        = './../data/lena.jpg'
IMG_GRAY            = './../data/lena_gray.jpg'
IMG_GRAY_640x512    = './../data/lena_gray_640x512.jpg'
IMG_RESULT          = './../data/lena_result.jpg'
IMG_RESULT_REVERSE  = './../data/lena_result_reverse.jpg'
sim_file            = './../data/lena.txt'
post_file           = './../sim/post_108.txt'

def read_img(img_file):
    img1 = cv2.imread(img_file)
    return img1

def rgb2gray(img_file):
    img1 = cv2.cvtColor(img_file,cv2.COLOR_RGB2GRAY)
    return img1

def show_img(image):
    cv2.imshow('image',image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def plt_show_img(image):
    plt.imshow(image)
    plt.xticks([])
    plt.yticks([])
    plt.show()


# 图像缩放函数
def img_resize(image,post_x,post_y):
    fx=1.6
    fy=1.2
    # post_image = cv2.resize(image,(0,0),fx=fx,fy=fy,interpolation=cv2.INTER_CUBIC)
    post_image = cv2.resize(image,(post_x,post_y))
    return post_image

def raw2Txt(image):
    np.savetxt(sim_file, image, fmt='%d', delimiter='\n')


def loadTxt(filename,nx,ny):
    a = np.loadtxt(filename,dtype=np.float64,usecols=(0), unpack=True).reshape((nx,ny))
    post_image_8bit = np.rint(a).astype(dtype='uint8')
    cv2.imwrite(IMG_RESULT,post_image_8bit)
    cv2.imwrite(IMG_RESULT_REVERSE,255-post_image_8bit)
    return post_image_8bit

def main():
    img = read_img(IMG_ORIGINAL)
    img2 = rgb2gray(img)
    cv2.imwrite(IMG_GRAY,img2)

    img3 = img_resize(img2,640,512)
    cv2.imwrite(IMG_GRAY_640x512,img3)

    show_img(img3)
    raw2Txt(img3)
    img4 = loadTxt(post_file,hidth,width)
    show_img(img4)

    show_img(255-img4)

if __name__ == "__main__":
    main()